package com.ygqh.baby.template;

import com.ygqh.baby.constant.Constant;
import com.ygqh.baby.utils.DateConvertUtils;

import java.util.Date;

/**
 * @author: sunshuo
 * @date: 2018/12/20 15:59
 */
public abstract class AbstractDiffDateTemplate<T> {

	private T t;

	private int cycle;

	private Date startDate;

	private Date referenceDate;

	public AbstractDiffDateTemplate(T t, int cycle, Date startDate, Date referenceDate) {
		this.t = t;
		this.cycle = cycle;
		this.startDate = startDate;
		this.referenceDate = referenceDate;
	}

	/**
	 * 返回最后一次执行时间
	 *
	 * @return
	 */
	public Date process() {
		long diff;
		boolean unitFlag;
		if (cycle >= Constant.STANDARD_DAYS_OF_MONTH) {
			// 按月统计
			String format = "yyyy-MM";
			diff = DateConvertUtils.diffMonths(DateConvertUtils.format(startDate, format), DateConvertUtils.format(referenceDate, format));
			startDate = DateConvertUtils.getMonthStartDate(startDate);
			unitFlag = true;
		} else { // 按天统计
			diff = DateConvertUtils.diffDayes(startDate, referenceDate) / cycle;
			unitFlag = false;
		}
		Date endDate;
		for (int i = 0; i < diff; i++) {
			if (unitFlag) {
				endDate = DateConvertUtils.addMonth(startDate, 1);
			} else {
				endDate = DateConvertUtils.addDay(startDate, cycle);
				if (!endDate.before(referenceDate)) {
					endDate = referenceDate;
				}
			}
			execute(startDate, endDate);
			startDate = endDate;
		}
		return startDate;
	}

	public abstract void execute(Date startDate, Date endDate);

}
